import { message } from 'ant-design-vue';
import router from '@/router/index.js';
import { getAssignedFileList } from '@/net/requ.js';

import { taskInfo, initColorMap, keydownCondPairs, trfNewline } from './common.js';
import { usePicSwitch } from './api/use-pic-switch.js';
import { listenKeydown } from './api/use-kbd-shortcut.js';

import { picState, fileContents, PicStateItem } from './api/use-task.js';
import { UserOpGte, useOpPerms } from './op-perms.js';
import { lastSelectIndex } from './api/use-layer.js';

export async function init() {
  taskInfo.value = JSON.parse(localStorage.getItem('taskInfo'));
  const pkgInfo = JSON.parse(localStorage.getItem('pkgInfo'));

  if (!(taskInfo.value && pkgInfo)) {
    message.error('请先选择任务');
    router.push({ path: '/task-detail', query: taskInfo.value.id });
    return;
  }

  taskInfo.value && initColorMap();

  const fileList = await getAssignedFileList( pkgInfo.pkg ).then( R.prop('data') );
  const idValid = R.compose(R.lt(-1), R.findIndex(R.propEq('id', pkgInfo.file)));
  if ( R.compose(R.not, idValid)(fileList) ) {
    pkgInfo.file = fileList[0].id;
    localStorage.setItem('pkgInfo', JSON.stringify(pkgInfo));
  }
  fileContents.value = R.map( R.prop('fileContent'), fileList );

  picState.value.i = fileList.findIndex(o => o.id == pkgInfo.file);
  document.querySelector('#label-area > p').innerHTML = trfNewline(fileContents.value[picState.value.i]);

  initPicState(fileList);
  usePicSwitch();
  listenKeydown();
  UserOpGte('查看') && useOpPerms();
}

export function initPicState(xs) {
  picState.value.list = xs.map(PicStateItem);
}

export function reset() {
  lastSelectIndex.value = 0;
  keydownCondPairs.length = 0;
}
